import time

import cv2  # Import OpenCV for image processing
import pyautogui

# branch

# Simulator window title (modify if needed)
window_title = "逍遥模拟器"

# Button and text coordinates (adjust based on your UI)
lack_button_x = 580
lack_button_y = 280
no_ticket_text_x = 880
no_ticket_text_y = 330

# Beep duration (seconds)
beep_duration = 2
# Loop count (adjust as desired)
loop_count = 100

# Loop counter
loop_counter = 0

while loop_counter < loop_count:
    # Click the "缺货登记" button
    pyautogui.click(x=lack_button_x, y=lack_button_y)

    # Wait for page load
    time.sleep(2)

    # Check if all rows show "无票"
    all_no_tickets = True
    for row_y in range(no_ticket_text_y + 20, no_ticket_text_y + 120, 30):
        # Capture a screenshot of the row's "无票" area
        row_screenshot = pyautogui.screenshot(region=(no_ticket_text_x, row_y, 100, 20))
        row_screenshot = cv2.cvtColor(row_screenshot, cv2.COLOR_BGR2GRAY)

        # Use template matching to find the "无票" text (adjust threshold as needed)
        no_ticket_template = cv2.imread("no_ticket_template.png", cv2.IMREAD_GRAYSCALE)
        result = cv2.matchTemplate(
            row_screenshot, no_ticket_template, cv2.TM_CCOEFF_NORMED
        )
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

        # Check if "无票" is found in the row (adjust threshold as needed)
        if max_val < 0.8:  # Adjust threshold for better accuracy
            all_no_tickets = False
            break  # Stop checking if any row doesn't have "无票"

    # Respond based on detection result
    if all_no_tickets:
        # Click the top-left triangle to go back (adjust coordinates if needed)
        pyautogui.click(x=20, y=20)

        # Wait for page load
        time.sleep(2)

        print("All rows show '无票'. Refreshing...")
    else:
        pyautogui.beep(duration=beep_duration)
        print("Some rows don't show '无票'. Beeping...")

    # Increment loop counter
    loop_counter += 1

print("Loop completed.")
